package com.mapfinal.server.local;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.imageio.ImageIO;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.geotools.renderer.lite.StreamingRenderer;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

import com.jfinal.render.Render;

public class MapRender extends Render {

	private Map<String, Object> paras;

	public MapRender(Map<String, Object> paras) {
		// TODO Auto-generated constructor stub
		this.paras = paras;
	}

	@Override
	public void render() {
		// TODO Auto-generated method stub
		LocalServerLayer layer = LocalServerManager.me().getServerLayer(paras.get("LAYERS").toString());
		if(layer==null) {
			return;
		}
		try {
			double[] bbox = (double[]) paras.get("bbox");
			double x1 = bbox[0], y1 = bbox[1], x2 = bbox[2], y2 = bbox[3];
			int width = (Integer) paras.get("width"), height = (Integer) paras.get("height");

			// 设置输出范围
			CoordinateReferenceSystem crs = CRS.decode("EPSG:3857");
			//GeoManager.me().getMap().getCoordinateReferenceSystem();
			//No code "EPSG:3857" from authority "EPSG" found for object of type "EngineeringCRS".
			ReferencedEnvelope mapArea = new ReferencedEnvelope(x1, x2, y1, y2, crs);
			// 初始化渲染器
			StreamingRenderer sr = new StreamingRenderer();
			sr.setMapContent(layer.getMap());
			// 初始化输出图像
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
			Graphics g = bi.getGraphics();
			((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			Rectangle rect = new Rectangle(0, 0, width, height);
			// 绘制地图
			sr.paint((Graphics2D) g, rect, mapArea);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			boolean flag = ImageIO.write(bi, "png", out);
			byte[] wmsByte = out.toByteArray();

			OutputStream os = response.getOutputStream();
			InputStream is = new ByteArrayInputStream(wmsByte);
			try {
				int count = 0;
				byte[] buffer = new byte[1024 * 1024];
				while ((count = is.read(buffer)) != -1) {
					os.write(buffer, 0, count);
				}
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				os.close();
				is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
